<template>
  <div class="map-wrap">
    <baidu-map
      :map-click="false"
      :scroll-wheel-zoom="true"
      :center="center"
      :zoom="zoom"
      class="bm-view"
      id="container"
      ak="BoXxIMrIkeuL8YqdKKl5woqtYHOm2iTa"
      @mousemove="syncPolygon"
      @zoomend='fnZoom'
      style="height:100%"
      @rightclick="newPolygon"
      @ready="handler"
    >
      <!-- 是否需要比例尺 -->
      <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>
      <!-- 缩放组件 -->
      <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
      <!-- 是否需要定位控件 -->
      <bm-geolocation
        anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
        :showAddressBar="true"
        :autoLocation="true"
      ></bm-geolocation>
      <!-- 左上角城市列表 -->
      <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>

      <!--默认标记点，标记窗体-->
      <!-- :content="marker.reg_type==7?'(在线) '+marker.alias:'(离线) '+marker.alias"-->
      <div v-if="averageCenter">
        <div v-for="(marker, index) in markers" :key="index">
          <bm-marker
            @rightclick="fnDelRight(marker)"
            @click="clickMarker($event, marker)"
            @mouseover="showCameraDetail(marker)"
            @mouseout="closeCameraDetail(marker)"
            :position="{ lng: marker.lng, lat: marker.lat }"
            :icon="{
              url:
                marker.online == 0
                  ? marker_icon0
                  : marker.online == 1
                  ? marker_icon1
                  : marker_icon_1,
              size: { width: 48, height: 48 },
            }"
          >
            <!-- <bm-label
              :content="marker.alias"
              :labelStyle="{
                background: 'rgb(0,0,0,0.6)',
                fontSize: '12px',
                color: '#fff',
                borderRadius: '5px',
                border: '1px solid #4677d4',
                padding: '3px',
              }"
              :offset="{ width: 40, height: 30 }"
          /> -->
          </bm-marker>
        </div>

        <!-- 悬停，显示信息窗体 -->
        <bm-info-window :show="show" :position="position">
          <div class="infoContent">
            <!-- <div class="show-sn">编号： {{ merkerInfo.sn }}</div> -->
            <div class="show-name">{{ merkerInfo.alias }}</div>
          </div>
        </bm-info-window>
        <!-- 点击，显示信息窗体 -->
        <bm-info-window
          class="con"
          :show="show_popup_video"
          :position="position"
        >
          <div class="click-popup-video">
            <div class="top-info">
              <!-- <div class="show-sn">编号： {{ merkerInfo.sn }}</div> -->
              <div class="show-name">名称： {{ merkerInfo.alias }}</div>
              <div class="show-name">经度： {{ merkerInfo.longitude }}</div>
              <div class="show-name">纬度： {{ merkerInfo.latitude }}</div>
            </div>
            <div class="video-box">
              <Video ref="myvideo" :url="url" />
            </div>
          </div>
        </bm-info-window>
        <!-- 自定义,中心点 -->
        <!--   <div class="marker-label">
          <img
            src="https://images.hbwlife.com/staticImg/map-center-icon.gif"
            alt
          />
        </div> -->
      </div>

      <!-- 聚合点 -->
      <!-- <bml-marker-clusterer v-if="averageCenter" :averageCenter="true">
        <div v-for="(marker, index) in markers" :key="index">
          <bm-marker
            @rightclick="fnDelRight(marker)"
            @click="clickMarker($event, marker)"
            @mouseover="showCameraDetail(marker)"
            @mouseout="closeCameraDetail(marker)"
            :position="{ lng: marker.lng, lat: marker.lat }"
            :icon="{
              url:
                marker.online == 0
                  ? marker_icon0
                  : marker.online == 1
                  ? marker_icon1
                  : marker_icon_1,
              size: { width: 48, height: 48 },
            }"
          >
          </bm-marker>
        </div>

        <bm-info-window :show="show" :position="position">
          <div class="infoContent">

            <div class="show-name">{{ merkerInfo.alias }}</div>
          </div>
        </bm-info-window>
        <bm-info-window
          class="con"
          :show="show_popup_video"
          :position="position"
        >
          <div class="click-popup-video">
            <div class="top-info">

              <div class="show-name">名称： {{ merkerInfo.alias }}</div>
              <div class="show-name">经度： {{ merkerInfo.longitude }}</div>
              <div class="show-name">纬度： {{ merkerInfo.latitude }}</div>
            </div>
            <div class="video-box">
              <Video ref="myvideo" :url="url" />
            </div>
          </div>
        </bm-info-window>
      </bml-marker-clusterer> -->
      <!-- 电子栅栏 -->
      <bm-polygon
        :path="path"
        v-for="(path, index) in polygonPath.paths"
        :key="index"
        stroke-color="blue"
        fill-color="red"
        :fill-opacity="0.8"
        :stroke-opacity="0.5"
        :stroke-weight="2"
      />
      <!-- 右侧选择打点，还是栅栏 -->
      <!-- <div class="paint">
        <div class="paint-item" :class="[type == 0 ? 'active' : '']">
          <i class="iconfont icon-dingwei" @click="fnSetPaint(0)" />
        </div>
        <div class="paint-item" :class="[type == 1 ? 'active' : '']">
          <i class="iconfont icon-pentagon" @click="fnSetPaint(1)" />
        </div>
        <div class="paint-item" :class="[type == 2 ? 'active' : '']">
          <span @click="fnSetPaint(2)">中心点</span>
        </div>
      </div>-->
    </baidu-map>
  </div>
</template>

<script>
//https://dafrok.github.io/vue-baidu-map/#/zh/start/installation
import axios from "axios";
import { getData, postData } from "@/request/http";
import bmScale from "vue-baidu-map/components/controls/Scale.vue";
import BaiduMap from "vue-baidu-map/components/map/Map.vue";
import bmNavigation from "vue-baidu-map/components/controls/Navigation";
import bmGeolocation from "vue-baidu-map/components/controls/Geolocation";
import bmCityList from "vue-baidu-map/components/controls/CityList";
import bmMarker from "vue-baidu-map/components/overlays/Marker";
import bmPolygon from "vue-baidu-map/components/overlays/Polygon";
import bmPolyline from "vue-baidu-map/components/overlays/Polyline";
import {
  BmlMarkerClusterer,
  BmInfoWindow,
  BmControl,
  BmLabel,
  BmScale
} from "vue-baidu-map";
import Video from "./VideoFlvMap";
//import Video from "./VideoMapLiveQing.vue";
export default {
  name: "Map",
  props: {
    averageCenter: {
      type: Boolean,
      default: true,
    }, // 是否使用聚合
    center: {
      type: Object,
      default() {
        return { lng: "", lat: "" };
        //return { lng: baseCenter.lng, lat: baseCenter.lat };
      },
    }, // 中心点
    marker: {
      type: Array,
      default() {
        return [];
      },
    },
    singleMark: {
      type: Boolean,
      default: true,
    },
    autoMarkers: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      markers: [],
      show: false, //鼠标悬停的窗体
      show_popup_video: false, //鼠标点击的窗体
      position: {},
      content: "",
      polyline: {
        editing: false,
        paths: [],
      },
      polygonPath: {
        editing: false,
        paths: [], // 绘制完成后的经纬度，其实是在画的时候动态push的，因为在点击的时候触发了 paintPolygon 函数
      },
      type: -1, // 0打点，1电子围栏
      paths: [], // 电子栅栏数组
      rightShow: false,
      positionRight: {},
      BMap: null,
      map: null,
      merkerInfo: {},
      zoom: 10,
      url: "",
      marker_icon0: require("@/assets/img/marker-icon0.png"),
      marker_icon1: require("@/assets/img/marker-icon1.png"),
      marker_icon_1: require("@/assets/img/marker-icon-1.png"),
      bPoints: [],
      distance: 0,
    };
  },
  mounted() {
    this.markers = this.marker;
  },
  computed:{
//    zoom(){
//      if(this.map){
//        return this.map.getZoom()
//      }
//      else{
//        return 10
//      }
//    }
  },


  methods: {
    //初始化
    handler({ BMap, map }) {
      this.map = map;
      this.BMap = BMap;
//      var center = map.getCenter();
      // this.markers = [{ lng: center.lng, lat: center.lat }];

//       this.zoom = 110;
      var zoom = map.getZoom();
      this.$emit("getCenter", {
        lat: baseCenter.lat,
        lng: baseCenter.lng,
        distance: 20 * 1000 * 3,
      });

//      拖拽
      if (map) {
        map.addEventListener("dragend", () => {
          var that = this;
          let map = this.map;
          var center = map.getCenter();
          var zoom = map.getZoom();
          var multiple = 3;
          if (zoom == 8) {
            this.zoom = 8;
            var distance = 50 * 1000 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 9) {
            this.zoom = 9;
            var distance = 25 * 1000 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 10) {
            this.zoom = 10;
            var distance = 20 * 1000 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 11) {
            //this.zoom = 11;
            var distance = 10 * 1000 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 12) {
            this.zoom = 12;
            var distance = 5 * 1000 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 13) {
            this.zoom = 13;
            var distance = 2 * 1000 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 14) {
            this.zoom = 14;
            var distance = 1 * 1000 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 15) {
            this.zoom = 15;
            var distance = 500 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 16) {
            this.zoom = 16;
            var distance = 200 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 17) {
            this.zoom = 17;
            var distance = 100 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 18) {
            //this.zoom = 18;
            var distance = 50 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom == 19) {
            //this.zoom = 19;
            var distance = 20 * multiple;
            that.$emit("getCenter", {
              lat: center.lat,
              lng: center.lng,
              distance: distance,
            });
          } else if (zoom < 8) {
            return;
          }
        });
      }

//      //滑轮
//      var scrollFunc = () => {
//        console.log('2189499832198498324989832489')
//          var that = this;
//
//      };
//      /*注册事件,滑轮*/
////      if (document.addEventListener) {
////        document.addEventListener("DOMMouseScroll", scrollFunc, false);
////      } //W3C
//      window.onmousewheel = document.onmousewheel = scrollFunc; //IE/Opera/Chrome
    },

    fnZoom(){
      if(this.map){
        var that = this;
        var center = this.map.getCenter();
        var zoom = this.map.getZoom();
        var multiple = 3;
        if (zoom == 8) {
          that.zoom = 8;
          that.distance = 50 * 1000 * multiple;
        } else if (zoom == 9) {
          that.zoom = 9;
          that.distance = 25 * 1000 * multiple;
        } else if (zoom == 10) {
          that.zoom = 10;
          that.distance = 20 * 1000 * multiple;
        } else if (zoom == 11) {
          that.zoom = 11;
          that.distance = 10 * 1000 * multiple;
        } else if (zoom == 12) {
          that.zoom = 12;
          that.distance = 5 * 1000 * multiple;
        } else if (zoom == 13) {
          that.zoom = 13;
          that.distance = 2 * 1000 * multiple;
        } else if (zoom == 14) {
          that.zoom = 14;
          that.distance = 1 * 1000 * multiple;
        } else if (zoom == 15) {
          that.zoom = 15;
          that.distance = 500 * multiple;
        } else if (zoom == 16) {
          that.zoom = 16;
          that.distance = 200 * multiple;
        } else if (zoom == 17) {
          that.zoom = 17;
          that.distance = 100 * multiple;
        } else if (zoom == 18) {
          that.zoom = 18;
          that.distance = 50 * multiple;
        } else if (zoom == 19) {
          that.zoom = 19;
          that.distance = 20 * multiple;
        }
//          console.log(that.distance)
        that.$emit("getCenter", {
          lat: center.lat,
          lng: center.lng,
          distance: that.distance,
        });
        this.map.setPosition(this.map.getCenter());
      }

    },

    // 自动缩放
    setZoom() {
//      var view = this.map.getViewport(eval(this.bPoints));
//      var mapZoom = view.zoom;
//      var centerPoint = view.center;
//      this.map.centerAndZoom(centerPoint, mapZoom);
    },

    // 点击地图事件
    getClickInfo(e) {
      if (this.singleMark) {
        console.log(e);
        this.markers = [
          {
            type: 0,
            lng: e.Ag.lng,
            lat: e.Ag.lat,
            id: new Date().getTime(),
          },
        ];
        let BMap = this.BMap;
        let geocoder = new BMap.Geocoder(); //创建地址解析器的实例
        geocoder.getLocation(e.point, (rs) => {
          this.$emit(
            "mark",
            Object.assign(
              {},
              {
                data: this.markers,
                info: Object.assign({
                  ...rs.addressComponents,
                  address: rs.address,
                }),
              }
            )
          );
        });
      } else {
        this.markers.push({
          type: 0,
          lng: e.Ag.lng,
          lat: e.Ag.lat,
          id: new Date().getTime(),
        });
        this.$emit("mark", Object.assign({}, { data: this.markers }));
      }
    },

    //删除框显示
    fnDelRight(item) {
      this.rightShow = true;
      this.positionRight = item;
    },

    //悬停悬停显示摄像机信息
    showCameraDetail(item) {
      console.log(1);
      this.show_popup_video = false;
      this.merkerInfo = item;
      this.position = item;
      this.show = true;
      /*  var BMap = this.BMap;
      var infoWindow = new BMap.InfoWindow(appendDiv); // 创建信息窗口对象
      infoWindow.addEventListener("open", function(type, target, point) {
        //窗口打开是，隐藏自带的关闭按钮
        $(".BMap_pop>img").css({ display: none });
      }); */
    },

    //点击摄像机sn，获取url
    getUrl(sn) {
      if (!sn) {
        return;
      }
      return new Promise((resolve, reject) => {
        postData("/adminweb/device/stream/live/url/ticket/lasted/unlimited", {
          sn: sn,
          ptl: "WS-FLV",
          channel: 0,
          sub: 0,
        })
          .then((res) => {
            resolve(res);
            console.log(res);
            this.url = res.datas.stream;
            this.show_popup_video = true;
          })
          .catch((res) => {
            reject("error");
            this.$message.error(res.code + "，" + res.msg);
          });
      });
    },

    //点击标记点，显示信息窗体
    clickMarker(e, item) {
      // console.log(e);
      this.merkerInfo = item;
      this.position = item;
      //   console.log(this.position);
      this.type = -1;
      this.polygonPath.editing = false;
      //   this.show_popup_video = true;
      this.show = false;
      this.content = item.lat;
      this.getUrl(item.sn);
      //   var steelOpts = {
      //     offset: new BMap.Size(0, -28), // 向上偏移
      //   };
      //   new BMap.InfoWindow(steelOpts);
      // this.url =
      //   "http://192.168.1.29:49000/YDT-ONVIF-251227033934680-DS-2DC2204IW-D3-W20191014CCCHD71815753W/0/0";
      this.$emit("show", item);
    },

    //鼠标移开，隐藏信息窗体
    closeCameraDetail(item) {
      this.show = false;
    },

    //确认删除标记点
    fnDel() {
      this.comDel();
      this.$emit("mark", this.markers);
    },

    //删除标记点，电子栅栏取消
    fnReset() {
      this.rightShow = false;
    },

    //删除方法
    comDel() {
      if (this.positionRight.type == 0) {
        let index = -1;
        let markers = this.markers;
        var rights = this.positionRight;
        if (markers.length > 0) {
          for (let i = 0; i < markers.length; i++) {
            let item = markers[i];
            if (item.id == rights["id"]) {
              index = i;
            }
          }
          if (index != -1) {
            this.markers.splice(index, 1);
            this.rightShow = false;
          }
        }
      }
    },

    //信息窗体打开
    infoWindowOpen() {
      this.show = true;
    },

    //信息窗体关闭
    infoWindowClose() {
      this.show = false;
    },

    // 鼠标移动时
    syncPolygon(e) {
      if (!this.polygonPath.editing) {
        return;
      }
      const { paths } = this.polygonPath;
      if (!paths.length) {
        return;
      }
      const path = paths[paths.length - 1];
      if (!path.length) {
        return;
      }
      if (path.length === 1) {
        path.push(e.point);
      }
      this.$set(path, path.length - 1, e.point);
    },

    // 鼠标右键
    newPolygon(e) {
      // this.rightShow = true
      // this.positionRight= e.Ag
      if (!this.polygonPath.editing) {
        return;
      }
      // 当开始绘制后把按钮调回开始绘制状态，防止绘制多个图形
      // this['polygonPath'].editing = !this['polygonPath'].editing
      const { paths } = this.polygonPath;
      if (!paths.length) {
        paths.push([]);
      }
      const path = paths[paths.length - 1];
      // path.pop()
      if (path.length) {
        paths.push([]);
      }
      this.$emit("path", this.paths);
    },
    infoWindowOpenRight() {
      this.rightShow = true;
    },
    infoWindowCloseRight() {
      this.rightShow = false;
    },
    // 鼠标点击
    /*     paintPolygon(e) {
      if (this.type == 0) {
        this.getClickInfo(e);
        this.polygonPath.editing = false;
      } else if (this.type == 1) {
        const { paths } = this.polygonPath;
        paths[paths.length - 1].push({
          type: 1,
          id: new Date().getTime(),
          lat: e.point.lat,
          lng: e.point.lng
        });
        var newpaths = paths.filter(item => {
          return item.length > 0;
        });
        this.paths = newpaths;
        this.polygonPath.editing = true;
      } else if (this.type == -1) {
      }
      this.$emit("getCenter", {
        lat: e.point.lat,
        lng: e.point.lng
      });
    } */

    /*
     * 点击右侧菜单
     * */
    // fnSetPaint(type) {
    //   if (type == this.type) {
    //     this.type = -1;
    //   } else {
    //     this.type = type;
    //   }
    // },
  },
  watch: {
    type(nVal) {
      if (nVal == 1) {
        const { paths } = this.polygonPath;
        paths.push([]);
      }
    },
    marker(nVal) {
      this.markers = nVal;
      this.bPoints = [];
      if (nVal.length > 0) {
        for (let i = 0; i < nVal.length; i++) {
          let item = nVal[i];
          var point = new this.BMap.Point(item.lng, item.lat);
          this.bPoints.push(point);
        }
      }
//      if (this.bPoints.length > 0) {
////        this.setZoom();
//      }
    },
  },
  components: {
    BaiduMap,
    bmScale,
    bmNavigation,
    bmGeolocation,
    bmCityList,
    bmMarker,
    BmlMarkerClusterer,
    BmInfoWindow,
    BmControl,
    bmPolyline,
    bmPolygon,
    BmLabel,
    Video,
  },
};
</script>

<style scoped>
@import "//at.alicdn.com/t/font_2270601_ya7zcdnbbrh.css";
.bm-view,
.map-wrap {
  width: 100%;
  height: calc(100vh - 180px);
  position: relative;
}
.paint {
  position: absolute;
  right: 80px;
  top: 20px;
  /* width: 120px; */
  width: auto;
  height: 50px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border: 2px solid #666666;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 0 10px #666;
}
.paint-item {
  width: 60px;
  height: 50px;
  box-sizing: border-box;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  float: left;
  cursor: pointer;
  border-right: 1px solid #d2d2d2;
}
.paint-item:last-child {
  border-right: none;
}
.iconfont {
  font-size: 26px;
  color: #2479b4;
}
.active {
  background-color: #2479b4;
}
.active .iconfont {
  color: #fff;
}

.BMap_bottom {
  display: none;
}
.BMap_pop > div,
.BMap_pop > img:nth-child(10) {
  display: none;
  overflow: unset;
}
.BMap_pop >>> div:nth-child(9) {
  display: block;
  overflow: unset;
  width: 340px !important;
}
.BMap_top {
  display: none;
}
.BMap_center {
  background: transparent;
  border: none;
  position: sticky !important;
  height: 100%;
}
.infoContent {
  border-radius: 5px;
  width: 200px;
  height: auto;
  padding: 20px 0 0 0;
}
.infoContent .show-sn {
  width: 100%;
  /* height: 50px;
  line-height: 50px; */
}
.infoContent .show-name {
  width: 100%;
  /* height: 50px;
  line-height: 50px; */
}
/* 点击弹窗中的video */
.click-popup-video {
  border-radius: 5px;
  width: 100%;
  height: 100%;
  margin-top: 10px;
  display: flex;
  flex-flow: column;
  justify-content: flex-start;
  align-items: center;
}
.click-popup-video .top-info {
  width: 100%;
  flex: 1;
}
.click-popup-video .show-sn {
  width: 100%;
  /* height: 50px;
  line-height: 50px; */
}

.click-popup-video .show-name {
  width: 100%;
  /* height: 50px;
  line-height: 50px; */
}
.click-popup-video .video-box {
  margin: 0 auto;
  margin-top: 10px;
  width: 100%;
  height: 150px;
  border: 1px solid #ccc;
  background: #000;
  /* opacity: 0.6; */
}
.info-window {
  padding-right: 8px;
  width: 100%;
  max-height: 280px;
  overflow: auto;
}
.el-divider {
  background: #ccccccbf;
}
.address {
  color: #000;
}
.info-window::-webkit-scrollbar {
  width: 6px;
  height: 1px;
}
.info-window::-webkit-scrollbar-thumb {
  border-radius: 6px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #535353;
}
.info-window::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 6px;
  background: #ededed;
}
.delInfor {
  margin-bottom: 10px;
  display: block;
  font-size: 14px;
  color: #676a6d;
}
/*  定位icon */
/* .marker-label {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.marker-label img {
  width: 80px;
  height: 80px;
} */
</style>

<style>
/* 去掉缩放上边的移动方位 */
.map-wrap .BMap_stdMpPan {
  display: none !important;
}
.map-wrap .BMap_pop {
  /* top: 5px !important; */
  /* z-index: 999 !important; */
}
.map-wrap .con {
  width: 220px;
  height: 200px;
}
</style>
